package com.jsyso.jadmin.sys.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.jsyso.jadmin.common.config.Global;
import com.jsyso.jadmin.common.security.Password;
import com.jsyso.jadmin.common.web.BaseController;
import com.jsyso.jadmin.sys.service.RoleService;
import com.jsyso.jadmin.sys.service.UserService;
import com.jsyso.jadmin.sys.utils.UserUtils;
import com.jsyso.jsyso.lang.JStringUtils;
import com.jsyso.jsyso.util.Callback;
import com.jsyso.jsyso.util.JsMap;
import com.jsyso.jsyso.web.JsMapParam;

/**
 * 用户控制器
 * @author janjan, xujian_jason@163.com
 *
 */
@Controller
@RequestMapping(value = "/a/sys/user")
public class UserController extends BaseController {
	
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;

	@ModelAttribute("user")
	public Object get(@RequestParam(
			required=false, defaultValue="0") Long id) {
		JsMap result = null;
		if(id != null && id > 0) 
			result = userService.get(id);
		if(result == null)
			result = JsMap.create(15)
			.set("id", 0)
			.set("loginName", "")
			.set("password", "")
			.set("name", "")
			.set("phone", "")
			.set("loginIp", "")
			.set("loginFlag", 1)
			.set("loginDate", "");
		return result.getBean();
	}
	
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = {"list", ""})
	public String list(
			HttpServletRequest request, HttpServletResponse response, Model model) {
		List<JsMap> list = userService.findList(JsMap.create("del_flag", Global.NO), "id DESC");
		model.addAttribute("list", list);
		return this.display("sys/user_list");
	}
	
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "form")
	public String form(
			Long id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		// 查询所有角色信息
		List<JsMap> roles = roleService.findList(JsMap.create("del_flag", Global.NO).set("status", Global.YES));
		// 当前用户已有角色
		List<JsMap> userRoles = userService.userRoleByUserId(id);
		model.addAttribute("userRoles", String.format("[%s]", JStringUtils.join(userRoles, ",", new Callback<JsMap, Object>() {
			public Object handle(JsMap param) {
				return param.get("roleId", Long.class);
			}
		})));
		model.addAttribute("roles", roles);
		return this.display("sys/user_form");
	}

	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "do_delete")
	public void doDelete(
			Long id,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if(id == null || id < 1)
			error(response, "参数错误");
		userService.delete(JsMap.create("id", id));
		success(response, "");
	}
	
	@RequiresPermissions("sys:user:edit")
	@RequestMapping(value = "do_save", method = RequestMethod.POST)
	public String doSave(
			JsMapParam user, 
			HttpServletRequest request, HttpServletResponse response, Model model) {
		JsMap data = user.getData();
		Long id = data.get("id", 0l, Long.class);
		Object rolesObject = data.remove("roles");
		String password = data.get("password", "", String.class)
				, oldPassword = data.remove("oldPassword").toString()
				, loginName = data.get("loginName", String.class);
		
		// 检查密码
		if(StringUtils.isBlank(password)) 
			return error(response, "密码不能为空！");
		// 加密密码
		if(!oldPassword.equals(password))
			data.set("password", Password.entryptPassword(password));
		
		// 保存用户
		if(id > 0) 
			userService.save(userService.keyRename(data));
		else 
			id = userService.add(userService.keyRename(data));
		
		// 保存用户角色关系
		String[] roles = rolesObject.getClass().isArray() ? (String[])rolesObject : new String[]{ rolesObject.toString() };
		List<JsMap> roleList = new ArrayList<JsMap>();
		for(String roleId : roles) {
			roleList.add(JsMap.create(2).set("role_id", Long.parseLong(roleId)).set("user_id", id));
		}
		userService.saveUserRoles(id, roleList);
		
		// 清除当前用户缓存
		if(loginName.equals(UserUtils.getUser().get("loginName", String.class)))
			UserUtils.clearCache();
		return success(response, "");
	}
	
	@RequestMapping(value = "update-pwd")
	public String updatePwd(
			HttpServletRequest request, HttpServletResponse response, Model model) {
		return this.display("sys/user_update_pwd");
	}
	
	@RequestMapping(value = "do_update_pwd")
	public String doUpdatePwd(
			String oldPassword,
			String newPassword,
			HttpServletRequest request, HttpServletResponse response, Model model) {
		if(StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword))
			return error(response, "参数错误");
		JsMap user = UserUtils.getUser();
		Long id = user.get("id", 0l, Long.class);
		// 验证旧密码
		if(!Password.validatePassword(oldPassword, user.get("password", "", String.class)))
			return error(response, "旧密码错误");
		// 修改密码
		userService.updatePasswordById(id, user.get("loginName", String.class), newPassword);
		return success(response, "");
	}
}
